package com.qlhx.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qlhx.Listener.Tools;
import com.qlhx.common.model.DataGridResult;
import com.qlhx.model.OpenDoorModel;
import com.qlhx.model.UEntranceGuard;
import com.qlhx.model.USwingCardRecord;
import com.qlhx.service.EntranceGuardService;
import com.qlhx.service.SwingCardRecordService;
import com.qlhx.util.ApiResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "门禁接口", description = "门禁接口")
@CrossOrigin(maxAge = 3600)
@RestController
@Scope(value = "prototype") 
@RequestMapping("entranceGuard")
public class EntranceGuardController {
	
	private  final Logger logger = LoggerFactory.getLogger(EntranceGuardController.class);
	
	@Autowired
	EntranceGuardService entranceGuardService;
	
	@Autowired
	SwingCardRecordService swingCardRecordService;
	
	@ApiOperation(value ="门禁信息更新" ,notes ="门禁信息更新")
	@RequestMapping(value = "/update",method = RequestMethod.POST, produces = {
    "application/json"}, consumes = {"application/json"})
	public @ResponseBody ApiResult<String> update(@RequestBody UEntranceGuard entranceGuard, HttpServletRequest request
			) 
	{
		ApiResult<String> result = new ApiResult<String>();
		UEntranceGuard temp = entranceGuardService.selectBySn(entranceGuard.getSn()+"");
		if(temp != null)
		{ 
			entranceGuard.setId(temp.getId());
			entranceGuardService.updateByPrimaryKeySelective(entranceGuard);
		}
		else
		{
			result.setCode(ApiResult.NOFOUND);
			result.setMsg("没有找个这个门禁");
		}
		return result; 
	}
	
	@RequestMapping(value = "list", method = RequestMethod.POST ,produces = { "application/json" })
	public @ResponseBody List<UEntranceGuard> list() {
		List<UEntranceGuard> list = entranceGuardService.list();
		return list;
	}
	
//	@ApiOperation(value ="门禁列表" ,notes ="门禁列表")
//	@RequestMapping(value = "/list" , method = RequestMethod.POST, produces = {
//    "application/json"}, consumes = {"application/json"})
//	public @ResponseBody DataGridResult list(ModelMap modelMap, Integer offset, Integer limit,@RequestHeader String token) 
//	{
////		logger.info("-------------------------");
////		RestTemplate rest = SpringUtil.getBean(RestTemplate.class);
////		rest.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
////	        try {
////	        	for(int i=0;i<20;i++)
////	        	{
////	        		ApiResult<String> res = rest.postForObject("http://service-control/contr/putlog/", String.format("接收到来自控制器SN = %d 的数据包..", i), ApiResult.class);
////			        logger.info("======="+res.getCode());
////	        	}
////	    } catch (Exception e) {
////	    	e.printStackTrace();
////	    	logger.error("连接基础微服务发生错误");
////	    }
//	        
////		ApiResult<List<UEntranceGuard>> result = new ApiResult<List<UEntranceGuard>>();
//		DataGridResult r = new DataGridResult();
//		try 
//		{
//			List<UEntranceGuard> list = entranceGuardService.list();
//			r.setTotal(list.size());
//			r.setRows(list);
////			result.setContent(list);
//		} catch (Exception e) 
//		{
//			e.printStackTrace();
//			logger.error("发送错误", e);
////			result.getErrorResult(e);
//		}
//		
//		
//		return r;
//		
//	}
	
	@ApiOperation(value ="根据sn查找门禁" ,notes ="根据sn查找门禁")
	@RequestMapping(value = "/detail/{sn}",method = RequestMethod.GET, produces = {
    "application/json"})
	public @ResponseBody ApiResult<UEntranceGuard> detail(@ApiParam("门禁SN") @PathVariable String sn, HttpServletRequest request
			) 
	{
		ApiResult<UEntranceGuard> result = new ApiResult<UEntranceGuard>();
		try 
		{
			UEntranceGuard entranceGuard = entranceGuardService.selectBySn(sn);
			result.setContent(entranceGuard);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统错误", e);
			result.getErrorResult(e);
		}
		
		return result;
	}
	
	@ApiOperation(value ="根据sn删除门禁" ,notes ="根据sn删除门禁")
	@RequestMapping(value = "/delete/{sn}",method = RequestMethod.GET, produces = {
    "application/json"})
	public @ResponseBody ApiResult<UEntranceGuard> delete(@ApiParam("门禁SN") @PathVariable String sn, HttpServletRequest request
			) 
	{
		ApiResult<UEntranceGuard> result = new ApiResult<UEntranceGuard>();
		try 
		{
			UEntranceGuard entranceGuard = entranceGuardService.selectBySn(sn);
			if(entranceGuard != null)
			{ 
				entranceGuardService.deleteByPrimaryKey(entranceGuard.getId());
			}
			else
			{
				result.setCode(ApiResult.NOFOUND);
				result.setMsg("没有找个这个门禁");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统错误", e);
			result.getErrorResult(e);
		}
		
		return result;
	}
	
//	@ApiOperation(value ="搜索门禁" ,notes ="搜索门禁")
//	@RequestMapping(value = "/search",method = RequestMethod.GET, produces = {
//    "application/json"})
//	public @ResponseBody ApiResult<String> search(HttpServletRequest request) 
//	{
//		ApiResult<String> result = new ApiResult<String>();
//		String msg = "";
//		DatagramSocket serverSocket = null;
//		try {
//			serverSocket = new DatagramSocket(61005);
//			serverSocket.setSoTimeout(10000);
//			for (int i = 0; i < 2; i++) 
//			{
//				
//				byte[] arr = new byte[1024];
//				DatagramPacket packet = new DatagramPacket(arr, arr.length);
//
//				// 3 当程序运行起来之后,receive方法会一直处于监听状态
//				 
//				serverSocket.receive(packet);
//				byte[] dataArr = packet.getData();
//				String ip = packet.getAddress().toString();
//				String sn_16 = HexUtil.bytesToHexFun3(dataArr[7]) + HexUtil.bytesToHexFun3(dataArr[6])
//						+ HexUtil.bytesToHexFun3(dataArr[5]) + HexUtil.bytesToHexFun3(dataArr[4]);
//				String sn =  Integer.parseInt(sn_16, 16)+"";
//				ip = ip.replace("/", "");
//				System.out.println(ip + "  " + Integer.parseInt(sn_16, 16));
//				
//				UEntranceGuard entranceGuard = entranceGuardService.selectBySn(sn);
//				if(entranceGuard == null)
//				{
//					entranceGuard = new UEntranceGuard();
//					entranceGuard.setIp(ip);
//					entranceGuard.setSn(sn);
//					entranceGuard.setCreatedate(new Date());
//					entranceGuardService.insertSelective(entranceGuard);
//					msg += " SN: "+sn + " IP: "+ip;
//				}
//			}
////			serverSocket.close();
//			if(StringUtils.isNotBlank(msg))
//			{
//				result.setContent("发现新门禁,已自动添加进数据库    "+msg);
//			}
//			else
//			{
//				result.setCode(ApiResult.NOFOUND);
//				result.setContent("没有发现新门禁");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			result.getErrorResult(e);
//		} 
//		finally {
//			if (serverSocket != null) {
//				serverSocket.close();
//			}
//
//		}
//
//		return result;
//	}
	
	@ApiOperation(value ="门禁开门" ,notes ="门禁开门")
	@RequestMapping(value = "/openDoor",method = RequestMethod.POST, produces = {
    "application/json"}, consumes = {"application/json"})
	public @ResponseBody ApiResult<String> openDoor(@ApiParam("门禁SN") @RequestBody OpenDoorModel openDoorModel, HttpServletRequest request
			) 
	{ 
		ApiResult<String> result = new ApiResult<String>();
		UEntranceGuard entranceGuard = entranceGuardService.selectBySn(openDoorModel.getSn()+"");
		if(entranceGuard != null)
		{ 
			int r = Tools.openDoor(entranceGuard.getIp(), openDoorModel.getSn(), openDoorModel.getDoorNo());
			if(r == 1)
			{
				result.setMsg("开门成功");
			}
			else
			{
				result.setMsg("开门失败");
				result.setCode(ApiResult.OPERATION_ERROR);
			}
		}
		else
		{
			result.setCode(ApiResult.NOFOUND);
			result.setMsg("开门失败，没有找个这个门禁");
		}
		
		
		return result;
	}
	
	@ApiOperation(value ="门禁状态" ,notes ="门禁状态")
	@RequestMapping(value = "/status",method = RequestMethod.POST, produces = {
    "application/json"}, consumes = {"application/json"})
	public @ResponseBody ApiResult<Map<String,String>> status(@ApiParam("门禁SN") @RequestBody OpenDoorModel openDoorModel, HttpServletRequest request
			) 
	{
		ApiResult<Map<String,String>> result = new ApiResult<Map<String,String>>();
		UEntranceGuard entranceGuard = entranceGuardService.selectBySn(openDoorModel.getSn()+"");
		if(entranceGuard != null)
		{ 
			Map r = Tools.status(entranceGuard.getIp(), openDoorModel.getSn());
			result.setContent(r);
		}
		else
		{
			result.setCode(ApiResult.NOFOUND);
			result.setMsg("没有找个这个门禁");
		}
		
		
		return result;
	}
	
	@ApiOperation(value ="刷卡记录" ,notes ="刷卡记录")
	@RequestMapping(value = "/record/{sn}",method = RequestMethod.GET, produces = {
    "application/json"})
	public @ResponseBody ApiResult<List<USwingCardRecord>> record(@ApiParam("门禁SN") @PathVariable String sn, HttpServletRequest request
			) 
	{
		if(sn.equals("{sn}"))
		{
			sn = null;
		}
		ApiResult<List<USwingCardRecord>> result = new ApiResult<List<USwingCardRecord>>();
		try 
		{
			List<USwingCardRecord> list = swingCardRecordService.list(sn);
			result.setContent(list);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统错误", e);
			result.getErrorResult(e);
		}
		
		return result;
	}
	
//	@RequestMapping(value = "/view")
//    public String view(Map<String, Object> map) {
//        map.put("name", "SpringBoot");
//        return "test";
//    }

}
